package com.wenkaihu.android.chess.socket;

import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.os.Handler;
import android.util.Log;

import com.wenkaihu.android.chess.model.PaceblePoint;
import com.wenkaihu.android.chess.view.SocketGoBang;

public class Server implements Runnable {
	public static final String SERVERIP = "localhost";
	public static final int SERVERPORT = 5558;
	private static final int REFRESH_MESSAGE = 51;
	private SocketGoBang sgobang;
	private Handler handler;
	
	public Server(SocketGoBang sgobang, Handler handler) {
		this.sgobang = sgobang;
		this.handler = handler;
	}
	
	public void run() {
		try {
			while (true) {
				ServerSocket serverSocket = new ServerSocket(SERVERPORT);
				Log.d("chess", "S #Start the Server ...");
				Socket client = serverSocket.accept();
				Log.d("chess", "S #Server start over");
				try {
					PaceblePoint pPoint = (PaceblePoint) 
						(new ObjectInputStream(client.getInputStream())).readObject();
					
					Log.d("chess", "S #Receive Point is#" + pPoint.toString());
					//Log.d("chess", "S the current pieces is#" + sgobang.getTotalSize());
					sgobang.addToAll(pPoint.getPointx(), pPoint.getPointy());
					handler.sendEmptyMessage(REFRESH_MESSAGE);
					serverSocket.close();
				} catch (Exception e) {
					Log.e("chess", "S #Get Exception #" + e);
				} finally {
					client.close();
					Log.d("chess", "S #Colse the Client!");
				}
			}
		} catch (Exception e) {
			Log.e("chess", "S #Get Exception #" + e);
		}
	}
}